//
// Created by zx208 on 2024/10/17.
//

//写出逆转线性单链表的算法

// 思路： 永远要记得 头插法是逆序 尾插法是顺序 所以这题我们要使用类似头插法进行插入

#include "../SingleLinkedList.h"

LinkedList Create_List_R(LinkedList head, int n){

    // 先创建头指针
    head = (LinkedList) malloc(sizeof( LNode));
    head->next = NULL;

    // 创建一个工作指针
    LinkedList node = head;

    for (int i = 0; i < n; ++i) {
        LinkedList p = (LinkedList) malloc(sizeof( LNode));
        int data;
        scanf(" %d", &data);
        p->data = data;
        p->next = node->next; // 即 p->next = NULL;
        node->next = p;
        node = p;
    }
    return head;
}

void PrintLL(LinkedList L){
    LNode *node = L->next;
    while(node){
        printf("%d ", node->data);
        node = node->next;
    }
}

LinkedList Reverse_LL(LinkedList L){
    LinkedList p = L->next, q = NULL, tmp = NULL;

    while(p){
        tmp = p->next;
        p->next = q;
        q = p;
        p = tmp;
    }
    return q;
}

int main(void){
    LinkedList L = NULL;
    L = Create_List_R(L, 5);
    L = Reverse_LL(L);
    PrintLL(L);
    return 0;
}

// 1 2 3 4 5